<template>
  <div class="create-article-container">
    <div class="page-header">
      <h2 class="page-title">{{ isEdit ? '编辑文章' : '发布新文章' }}</h2>
      <el-button 
        type="primary" 
        @click="openDrafts"
        v-if="isLoggedIn"
      >
        <el-icon><Document /></el-icon>我的草稿
        <el-badge v-if="draftCount > 0" :value="draftCount" class="draft-badge" />
      </el-button>
    </div>
    
    <el-form :model="articleForm" :rules="rules" ref="articleFormRef" label-width="80px" @submit.prevent>
      <el-form-item label="标题" prop="title">
        <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      
      <el-form-item label="板块" prop="boardId">
        <el-select v-model="articleForm.boardId" placeholder="请选择板块">
          <el-option
            v-for="board in boards"
            :key="board.id"
            :label="board.name"
            :value="board.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="标签" prop="tags">
        <el-input v-model="articleForm.tags" placeholder="请输入文章标签，多个标签用逗号分隔"></el-input>
      </el-form-item>
      
      <el-form-item label="摘要" prop="summary">
        <el-input
          type="textarea"
          v-model="articleForm.summary"
          :rows="3"
          placeholder="请输入文章摘要"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          v-model="articleForm.content"
          :rows="15"
          placeholder="请输入文章内容"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          @click.prevent="() => { console.log('CLICKED: 发布文章按钮'); submitForm(); }" 
          :loading="submitting"
        >{{ isEdit ? '保存修改' : '发布文章' }}</el-button>
        
        <el-button 
          id="save-draft-btn" 
          @click.prevent="() => { console.log('CLICKED: 保存草稿按钮'); saveAsDraft(); }" 
          :loading="savingDraft"
        >保存为草稿</el-button>
        
        <el-button 
          @click.prevent="() => { console.log('CLICKED: 取消按钮'); goBack(); }"
        >取消</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 草稿列表抽屉 -->
    <el-drawer
      title="我的草稿"
      v-model="showDrafts"
      direction="rtl"
      size="50%"
    >
      <div class="drafts-container">
        <el-empty v-if="drafts.length === 0" description="暂无草稿"></el-empty>
        <el-table v-else :data="drafts" style="width: 100%">
          <el-table-column prop="title" label="标题" min-width="180"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="editDraft(scope.row)">编辑</el-button>
              <el-button type="success" size="small" @click="publishDraft(scope.row.id)">发布</el-button>
              <el-button type="danger" size="small" @click="deleteDraft(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import api from '@/api/index'
import { formatDate } from '@/utils/dateUtils'

export default {
  name: 'CreateArticle',
  
  components: {
    Document
  },
  
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    
    const articleFormRef = ref(null)
    const submitting = ref(false)
    const savingDraft = ref(false)
    const boards = ref([])
    const isEdit = computed(() => route.params.id)
    const showDrafts = ref(false)
    const drafts = ref([])
    const draftCount = computed(() => store.getters['article/getDraftCount'])
    
    // 检查用户是否登录
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    
    const articleForm = reactive({
      title: '',
      boardId: '',
      content: '',
      tags: '',
      summary: ''
    })
    
    const rules = {
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
      ],
      boardId: [
        { required: true, message: '请选择板块', trigger: 'change' }
      ],
      tags: [
        { required: false, message: '请输入文章标签', trigger: 'blur' }
      ],
      summary: [
        { required: false, message: '请输入文章摘要', trigger: 'blur' },
        { min: 10, message: '摘要至少10个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' },
        { min: 10, message: '内容至少10个字符', trigger: 'blur' }
      ]
    }
    
    // 加载板块列表
    const loadBoards = async () => {
      try {
        const response = await api.board.getAllBoards()
        if (response.code === 0) {
          boards.value = response.data || []
        }
      } catch (error) {
        console.error('加载板块失败:', error)
        ElMessage.error('加载板块失败，请刷新页面重试')
      }
    }
    
    // 加载草稿列表
    const loadDrafts = async () => {
      try {
        await store.dispatch('article/getUserDrafts')
        drafts.value = store.getters['article/getDrafts']
      } catch (error) {
        console.error('加载草稿失败:', error)
        ElMessage.error('加载草稿失败，请重试')
      }
    }
    
    // 加载草稿数量
    const loadDraftCount = async () => {
      try {
        await store.dispatch('article/countUserDrafts')
      } catch (error) {
        console.error('加载草稿数量失败:', error)
      }
    }
    
    // 打开草稿列表
    const openDrafts = async () => {
      try {
        // 尝试加载草稿，并在成功后打开面板
        console.log('尝试加载草稿列表');
        await loadDrafts();
        
        // 检查是否获取到草稿
        if (drafts.value && drafts.value.length > 0) {
          console.log(`成功加载 ${drafts.value.length} 个草稿`);
        } else {
          console.log('草稿列表为空');
        }
        
        // 无论是否有草稿，都显示面板
        showDrafts.value = true;
      } catch (error) {
        console.error('打开草稿列表失败:', error);
        ElMessage.error('无法加载草稿列表，请刷新页面重试');
      }
    }
    
    // 编辑草稿
    const editDraft = (draft) => {
      articleForm.title = draft.title || ''
      articleForm.boardId = draft.boardId || ''
      articleForm.content = draft.content || ''
      articleForm.tags = draft.tags || ''
      articleForm.summary = draft.summary || ''
      articleForm.draftId = draft.id
      showDrafts.value = false
      
      ElMessage.success('草稿已加载，可继续编辑')
    }
    
    // 发布草稿
    const publishDraft = async (draftId) => {
      try {
        const result = await ElMessageBox.confirm(
          '确定要发布这篇草稿吗？发布后草稿将被删除。',
          '发布确认',
          {
            confirmButtonText: '确定发布',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          console.log('用户确认发布草稿，ID:', draftId)
          try {
            const articleId = await store.dispatch('article/publishDraft', draftId)
            console.log('草稿发布结果，文章ID:', articleId)
            
            if (articleId) {
              ElMessage.success('草稿发布成功！')
              await loadDraftCount()
              await loadDrafts()
              
              // 确保文章ID有效
              if (articleId && typeof articleId === 'number' && articleId > 0) {
                // 跳转到文章详情页
                ElMessage.success('正在跳转到文章详情页...')
                router.push({ name: 'ArticleDetail', params: { id: articleId } })
              } else {
                // 如果返回的文章ID无效，就回到首页
                console.log('返回的文章ID无效或无法访问，返回首页')
                ElMessage.success('草稿已成功发布，返回首页查看')
                router.push({ name: 'Home' })
              }
            } else {
              console.error('草稿发布失败：文章ID为空或无效')
              ElMessage.error('草稿发布失败，请重试')
            }
          } catch (actionError) {
            console.error('草稿发布操作异常:', actionError)
            ElMessage.error(`草稿发布错误: ${actionError.message || '未知错误'}`)
          }
        } else {
          console.log('用户取消发布草稿')
        }
      } catch (error) {
        console.error('发布草稿对话框异常:', error)
        ElMessage.error('操作被取消')
      }
    }
    
    // 删除草稿
    const deleteDraft = async (draftId) => {
      try {
        const result = await ElMessageBox.confirm(
          '确定要删除这篇草稿吗？删除后无法恢复。',
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          const success = await store.dispatch('article/deleteDraft', draftId)
          if (success) {
            ElMessage.success('草稿已删除')
            await loadDraftCount()
            await loadDrafts()
          } else {
            ElMessage.error('草稿删除失败，请重试')
          }
        }
      } catch (error) {
        console.error('删除草稿时出错:', error)
      }
    }
    
    // 保存为草稿
    const saveAsDraft = async () => {
      if (articleForm.title.trim() === '' && articleForm.content.trim() === '') {
        ElMessage.warning('标题和内容不能同时为空')
        return
      }
      
      savingDraft.value = true
      
      try {
        // 构造草稿数据
        const draftData = {
          id: articleForm.draftId, // 如果是编辑草稿，会有草稿ID
          title: articleForm.title,
          content: articleForm.content,
          boardId: articleForm.boardId || null,
          tags: articleForm.tags,
          summary: articleForm.summary,
          isDraft: true // 明确标记这是草稿
        }
        
        // 如果没有选择板块，使用默认板块或提示
        if (!draftData.boardId) {
          if (boards.value && boards.value.length > 0) {
            draftData.boardId = boards.value[0].id;
            ElMessage.info('使用默认板块保存草稿');
          } else {
            ElMessage.warning('请选择一个板块');
            savingDraft.value = false;
            return;
          }
        }
        
        console.log('开始保存草稿...', draftData);
        const draftId = await store.dispatch('article/saveDraft', draftData)
        console.log('保存草稿返回的ID:', draftId);
        
        if (draftId) {
          // 更新表单中的草稿ID，方便继续编辑
          articleForm.draftId = draftId
          // 更新草稿数量
          await loadDraftCount()
          
          // 显示成功消息，但不进行任何跳转
          ElMessage({
            message: '草稿保存成功',
            type: 'success',
            duration: 3000
          })
          
          // 显示草稿ID，帮助用户知道草稿已保存
          console.log('草稿已保存，ID:', draftId);
        } else {
          ElMessage.error('草稿保存失败，请重试')
        }
      } catch (error) {
        console.error('保存草稿失败:', error)
        ElMessage.error(`保存草稿失败: ${error.message || '未知错误'}`)
      } finally {
        savingDraft.value = false
      }
    }
    
    // 提交表单发布文章
    const submitForm = async () => {
      if (!articleFormRef.value) return
      
      articleFormRef.value.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请完善文章信息')
          return
        }
        
        submitting.value = true
        
        try {
          const articleData = {
            title: articleForm.title,
            content: articleForm.content,
            boardId: articleForm.boardId,
            tags: articleForm.tags,
            summary: articleForm.summary,
            isDraft: false // 明确标记不是草稿
          }
          
          if (isEdit.value) {
            // 编辑文章
            articleData.id = route.params.id
            console.log('DEBUG: 编辑文章，发送数据:', JSON.stringify(articleData))
            await api.article.update(articleData)
            ElMessage.success('文章更新成功')
            router.push({ name: 'ArticleDetail', params: { id: route.params.id } })
          } else {
            // 发布新文章 - 改用store.dispatch而不是直接调用API
            console.log('DEBUG: 即将通过store.dispatch创建文章，数据:', JSON.stringify(articleData));
            
            const articleId = await store.dispatch('article/create', articleData);
            console.log('文章创建结果，文章ID:', articleId);
            
            if (articleId) {
              ElMessage.success('文章发布成功')
              
              // 如果是从草稿发布，删除草稿
              if (articleForm.draftId) {
                await store.dispatch('article/deleteDraft', articleForm.draftId)
                await loadDraftCount()
              }
              
              // 跳转到文章详情页而不是首页
              if (typeof articleId === 'number' && articleId > 0) {
                router.push({ name: 'ArticleDetail', params: { id: articleId } })
              } else {
                // 如果articleId不是有效的数字，则回到首页
                console.warn('文章ID无效，返回首页:', articleId)
                router.push({ name: 'Home' })
              }
            } else {
              ElMessage.error('发布失败，请重试')
            }
          }
        } catch (error) {
          console.error('发布文章失败:', error)
          ElMessage.error('发布失败，请重试')
        } finally {
          submitting.value = false
        }
      })
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 如果是编辑模式，加载文章数据
    const loadArticle = async (id) => {
      try {
        const article = await store.dispatch('article/getArticleDetail', id)
        if (article) {
          articleForm.title = article.title
          articleForm.content = article.content
          articleForm.boardId = article.boardId
          articleForm.tags = article.tags || ''
          articleForm.summary = article.summary || ''
        } else {
          ElMessage.error('加载文章失败，请重试')
          router.push({ name: 'Home' })
        }
      } catch (error) {
        console.error('加载文章数据失败:', error)
        ElMessage.error('加载文章失败，请重试')
        router.push({ name: 'Home' })
      }
    }
    
    onMounted(async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        router.push({ name: 'Login', query: { redirect: route.fullPath } })
        return
      }
      
      await loadBoards()
      await loadDraftCount()
      
      if (isEdit.value) {
        await loadArticle(route.params.id)
      }
    })
    
    return {
      articleFormRef,
      articleForm,
      rules,
      submitting,
      savingDraft,
      boards,
      isEdit,
      submitForm,
      saveAsDraft,
      goBack,
      showDrafts,
      drafts,
      draftCount,
      openDrafts,
      editDraft,
      publishDraft,
      deleteDraft,
      formatDate,
      isLoggedIn
    }
  }
}
</script>

<style scoped>
.create-article-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.draft-badge {
  margin-left: 8px;
}

.drafts-container {
  padding: 20px;
}
</style>